import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { UserEntity } from '../user.entity'
import NodeAuth from 'node-auth0'
import { RedisUtilsService } from 'src/modules/redis-utils/redis-utils.service'
import * as jwt from 'jsonwebtoken'
@Injectable()
export class LoginService {
  constructor(
    @InjectRepository(UserEntity) private userRepository: Repository<UserEntity>,
    private readonly redisUtilsService: RedisUtilsService
  ) {
    this.nodeAuth = new NodeAuth()
  }

  private nodeAuth: NodeAuth

  //jwt
  // async login(data:any){
  //    const {username,password} = data
  //    const users = await this.userRepository.find({where:{username}})
  //    if(users.length>0){
  //      const user = users.find(v=>this.nodeAuth.checkPassword(password,v.password))
  //      console.log('user---',user);
  //      if(!user) return '用户名或密码不正确'
  //      return user.toResponseObject(true)
  //    }else{
  //      return '用户名或密码不正确'
  //    }
  // }

  //redis
  async login(data: any) {
    const { username, password } = data
    const users = await this.userRepository.find({ where: { username } })
    console.log('====ysers====',users);
    if (users.length > 0) {
      const user = users.find(v => this.nodeAuth.checkPassword(password, v.password))
      if (!user) return '用户名或密码不正确'
      const token = jwt.sign({
        id: user.id,
      },
        process.env.SECRET,
        {
          expiresIn: '1d'
        }
      )
      const redisData = {
        token,
        user
      }
      this.redisUtilsService.set(String(user.id),redisData)
      return Object.assign(user,{token})
    } else {
      return '用户名或密码不正确'
    }
  }

}
